package com.manager.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelUtil {

	/*
	 * 导出为Excel到服务器根目录/excel文件中，以做记录，并通过浏览器下载
	 * 注意，任何一列不能有null值出现，否则导出失败
	 */
	public static void getExcel(List list, HttpServletRequest request, HttpServletResponse response){
		StringBuffer baseRealPath = new StringBuffer(request.getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/"));
		FileUtil.createFolder(baseRealPath.append("/excelTemp").toString());
		String filePath = baseRealPath.append("/").append(DateUtil.getCurrentDateTime(false)).append(".xls").toString();
		
		WritableWorkbook book = null;
		
		try {
			//excel文件生成开始
			File desFile = new File(filePath);
			book = Workbook.createWorkbook(desFile);
			WritableSheet sheet = book.createSheet("Sheet_0", 0);
			
			for(int i = 0; i < list.size(); i++){
				Map m = (Map)list.get(i);
				Iterator it = m.entrySet().iterator();
				
				int j = 0;
				while(it.hasNext()){
					Entry entry = (Entry)it.next();
					Label label = null;
					if(i == 0){
						//生成标题
						label = new Label(j, i,entry.getKey().toString());
						sheet.addCell(label);
					}
					//生成内容
					label = new Label(j, i + 1, m.get(entry.getKey()).toString());
					sheet.addCell(label);
					j++;
				}
			}
			
			book.write();
			book.close();
			//excel文件生成结束
			
			//开始下载
	        InputStream inStream = new FileInputStream(desFile);// 文件的存放路径
	        response.reset();
	        response.setContentType("bin");
	        response.addHeader("Content-Disposition", "attachment; filename=\"" + FileUtil.getPrefix(desFile.getName()) + ".xls\"");
	        byte[] b = new byte[100];
	        int len;
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		
	}
}
